package com.szt.ynb.server.router.schedule;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.szt.ynb.server.router.entity.Server;
import com.szt.ynb.server.router.service.ServerService;

@Component
public class StatusCheckSchedule {
	
	@Autowired
	private ServerService serverService;
	
	/***
	 * 3秒执行一次,状态检查，评分和下线过期服务
	 */
	@Scheduled(fixedRate = 3000)
	public void run() {
		// >30秒，未更新上线状态，服务评分设置为70;
		// >60秒，未更新上线状态，服务评分设置为50;
		// >90秒，未更新上线状态，服务评分设置为0分，并下线服务
		Date now = new Date();
		Date dateAdd30s = DateUtils.addSeconds(now, -30);
		Date dateAdd60s = DateUtils.addSeconds(now, -60);
		Date dateAdd90s = DateUtils.addSeconds(now, -90);
		List<Server> serverList = serverService.findAll();
		for (Server server : serverList) {
			if (server.getStatus() == Server.STATUS_ONLINE) {
				if (server.getUpdateDate().before(dateAdd30s)) {
					server.setScore(70);
				}
				if (server.getUpdateDate().before(dateAdd60s)) {
					server.setScore(50);
				}
				if (server.getUpdateDate().before(dateAdd90s)) {
					server.setScore(0);
					server.setStatus(Server.STATUS_OFFLINE);
				}
				serverService.save(server);
			}
		}
	}
	
}
